import React, {
	useEffect,
	useMemo,
	useRef,
	useState,
	useImperativeHandle,
} from 'react'
import moment from 'moment'
import {Button, Form, message, Steps, Radio, Input} from 'antd'
import {connect, history} from 'umi'
import {Basics} from '../components'
import EditTb from '../components/editTb'
import Tb from '../components/tb'
import Styles from './index.less'

import {
	auditFlow,
	channelinnovationrewardsDetail,
	commodityDetail,
	saveSubmitFlow,
	updateSubmitFlow,
	getHistory,
} from '@/service/merchantCenter/channelRule'
import Examine from '@/components/Examine'
// import Modal from '@/components/Modal'
// import {historyList} from '@/service/purchase/initiation'
import {getProvinceDataByCityName} from '@/service/common'
import {processRecordSave} from '@/service/common/index'

const {Step} = Steps
const {TextArea} = Input

const add = (props: {location: any; queryType: any; user: any; cRef: any}) => {
	const {location, queryType, user, cRef} = props
	const routerQuery = queryType || location.query
	const clueId = routerQuery.id

	const pageType = useMemo(() => routerQuery.pageType, [routerQuery])
	const [shwos, setShows] = useState(false)
	const [auditHistory, setAuditHistory] = useState([])
	const [auditstate, setAuditstate] = useState() // 审核状态
	const [notes, setNotes] = useState() // 审核意见
	const examineRef = useRef<any>(null)
	useEffect(() => {
		if (pageType === 'audit' || pageType === 'detail') {
			setShows(true)
			getHistory(routerQuery?.id).then((res: any) => {
				setAuditHistory(res?.data)
				if (res?.success) {
					setAuditHistory(res?.data)
				}
			})
			// window.location.reload()
		} else {
			setShows(false)
		}
	}, [])
	const [rederT, setRnderT] = useState(false)
	const [loading, setLoading] = useState(false)
	const [detailRecord, setDetailRecord] = useState<any>({})

	const [formsO, setFormsO] = useState([])
	const [formsN, setFormsN] = useState([])
	const [numberAndAmountList, setNumberAndAmountList] = useState<any>([
		{
			correspondingLadder: '1',
			number: '',
			amount: '',
			ladderBd: '',
		},
	])
	const [offsetNumberAndAmountList, setOffsetNumberAndAmountList] =
		useState<any>([
			{
				correspondingLadder: '1',
				number: '',
				amount: '',
				ladderBd: '',
			},
		])
	const [basicsForm] = Form.useForm()

	const [edType, setEdType] = useState(1)

	const [selectedRow, setSelectedRow] = useState<any[]>([])

	// const [btnLoading, setBtnLoading] = useState(false)

	useEffect(() => {
		if (pageType) {
			channelinnovationrewardsDetail({ids: clueId}).then((res: any) => {
				if (res.success) {
					setEdType(res?.data.innovationRewards.channelTypeTwo)
					const newData = res?.data.innovationRewards

					if (newData?.cityName) {
						getProvinceDataByCityName({
							cityName: newData.cityName,
						}).then((result: any) => {
							if (result.data) {
								setDetailRecord({
									...newData,
									cityId: [
										result?.data?.provinceId,
										newData?.cityId,
									],
								})
							}
						})
					}
					const newNumberAndAmountList: any = []
					const newOffsetNumberAndAmountList: any = []
					res.data.rewardRules.forEach((item: any) => {
						// eslint-disable-next-line no-param-reassign
						item.correspondingLadder =
							item.correspondingLadder.toString()
						if (item.type === 0) {
							newNumberAndAmountList.push(item)
						}
						if (item.type === 1) {
							newOffsetNumberAndAmountList.push(item)
						}
					})
					setNumberAndAmountList(newNumberAndAmountList)
					setOffsetNumberAndAmountList(newOffsetNumberAndAmountList)
				}
			})

			commodityDetail({ids: clueId}).then((res: any) => {
				if (res.success) {
					setSelectedRow(res.data.ids)
					setRnderT(true)
				}
			})
		}
	}, [])

	const andAmount = useMemo(
		() =>
			numberAndAmountList.length + offsetNumberAndAmountList.length === 1,
		[numberAndAmountList, offsetNumberAndAmountList],
	)
	// eslint-disable-next-line no-param-reassign
	const onSave = async (callback?: any) => {
		setLoading(true)
		try {
			const basicsFormData = await basicsForm.validateFields()
			const data = {...basicsFormData}
			data.startDate = moment(data.startDate).format('YYYY-MM-DD')
			data.endDate = moment(data.endDate).format('YYYY-MM-DD')
			if (data?.cityId) {
				data.cityId = data?.cityId?.[1] || data?.cityId
			}
			let err = 0
			const newNumberAndAmountList = [...numberAndAmountList]
			const newOffsetNumberAndAmountList = [...offsetNumberAndAmountList]
			let numberStatus = true
			let offsetNumberStatus = true
			numberAndAmountList?.some((item: any, index: number) => {
				const newData = newNumberAndAmountList?.find(
					(items: any, newIndex: number) =>
						index > newIndex && item?.number <= items?.number,
				)
				if (newData) {
					message.warning('阶梯上限数量应大于前一个阶梯上限数量')
					numberStatus = false
					return true
				}
				return false
			})
			offsetNumberAndAmountList?.some((item: any, index: number) => {
				const newData = newOffsetNumberAndAmountList?.find(
					(items: any, newIndex: number) =>
						index > newIndex && item?.number <= items?.number,
				)
				if (newData) {
					message.warning('阶梯下限数量应大于前一个阶梯下限数量')
					offsetNumberStatus = false
					return true
				}
				return false
			})
			if (numberStatus && offsetNumberStatus) {
				numberAndAmountList.forEach((item: any) => {
					if ([4, 5].includes(edType)) {
						if (!item.number || !item.amount || !item.ladderBd) {
							err += 1
						}
					} else if (!item.number || !item.amount) {
						err += 1
					}
				})
				offsetNumberAndAmountList.forEach((item: any) => {
					if (!item.number || !item.amount) {
						err += 1
					}
				})
				if (err !== 0) {
					message.error('奖励不能为空')
					setTimeout(() => setLoading(false), 1000)
					return Promise.reject()
				}
				if (offsetNumberAndAmountList.length) {
					const arr = offsetNumberAndAmountList.map((item: any) => {
						if (Number(item?.ladderBd)) {
							return `${item.number}-${item.amount}-${item.ladderBd}-${item.correspondingLadder}`
						}
						return `${item.number}-${item.amount}-${item.correspondingLadder}`
					})
					data.offsetNumberAndAmountList = arr
				} else {
					data.offsetNumberAndAmountList = []
				}
				if (numberAndAmountList.length) {
					const arr = numberAndAmountList.map((item: any) => {
						if (Number(item?.ladderBd)) {
							return `${item.number}-${item.amount}-${item.ladderBd}-${item.correspondingLadder}`
						}
						return `${item.number}-${item.amount}-${item.correspondingLadder}`
					})
					data.numberAndAmountList = arr
				} else {
					data.numberAndAmountList = []
				}
				data.commodityList = selectedRow
				if (pageType) {
					const res = await updateSubmitFlow({
						...data,
						id: clueId,
					})
					if (res.success) {
						history.push({
							pathname: '/merchantCenter/channelRule/list',
						})
						message.success('修改成功')
					} 
				} else {
					if (routerQuery.type === '1') {
						data.commodityType = routerQuery.type
						data.commodityTypeNo = routerQuery.onlyCode
					}
					const res = await saveSubmitFlow(data)
					if (res.success) {
						message.success('新增成功')
						if (routerQuery.type === '1') {
							callback(true)
						} else {
							history.push({
								pathname: '/merchantCenter/channelRule/list',
							})
						}
					} 
				}
				setTimeout(() => setLoading(false), 1000)
			} else {
				setTimeout(() => setLoading(false), 1000)
			}
		} catch (error) {
			setTimeout(() => setLoading(false), 1000)
		}
		return false
	}

	useImperativeHandle(cRef, () => ({
		onSubmit: (e: any) => {
			onSave(e)
		},
	}))
	// const examineRef = useRef<any>(null)

	// const [isExamineModalOpen, setIsExamineModalOpen] = useState(false)
	// const [examineType, setExamineType] = useState<string>('')

	const callBack = () => {}

	/** 审核 */
	const onCompleteTask = async () => {
		if(auditstate===2){
			processRecordSave({
				bizType: 14,
				bizNo: routerQuery?.id,
				processId:routerQuery.processId,
			})
		}
		// setBtnLoading(true)
		// const examineData = await examineRef.current.getData()
		// let pass = ''
		// if (examineType === '拒绝') pass = '3'
		// if (examineType === '同意') pass = '1'
		// if (examineType === '驳回') pass = '2'
		if (auditstate) {
			const res = await auditFlow({
				businessId: clueId,
				instanceId: routerQuery?.processInstanceId,
				pass: auditstate,
				message: notes,
			})
			if (res.success) {
				message.success(res.msg)
				history.goBack()
				// setBtnLoading(false)
			} 
		} else {
			message.error('请选择审核状态')
		}
	}
	// const types = useMemo(() => routerQuery?.examine === 'true', [routerQuery])
	// 审核状态
	const auditonChange = (e: any) => {
		setAuditstate(e.target.value)
	}
	// 审核意见
	const onTextChange = (e: any) => {
		setNotes(e.target.value)
	}
	return (
		<div className={Styles.add}>
			{shwos ? (
				<div className={Styles.basics}>
					{/* <div className={Styles.titleBox}>审批信息</div>
					<div className={Styles.steps}>
						<Steps
							current={
								auditHistory?.findIndex(
									(item: any) => item.nodeType === 2,
								) === -1
									? auditHistory.length - 1
									: auditHistory?.findIndex(
											(item: any) => item.nodeType === 2,
									  )
							}
							size="small">
							{auditHistory?.map((res: any) => (
								<Step
									title={res?.activityName}
									subTitle={
										<>
											<div>{res.assigneeName}</div>
											<div>{res.endTime}</div>
											<div>{res.message}</div>
										</>
									}
								/>
							))}
						</Steps>
					</div> */}
					{pageType === 'audit' && (
						<>
						<div className={Styles.titleBox}>审批状态</div>
							<div className={Styles.stepstate}>
								<span>审核状态：</span>
								<Radio.Group
									onChange={auditonChange}
									value={auditstate}>
									<Radio value={1}>审核通过</Radio>
									<Radio value={2}>审核驳回</Radio>
								</Radio.Group>
							</div>
							<div className={Styles.stepstate}>
								<span>处理意见：</span>
								<TextArea
									style={{maxWidth: '700px'}}
									value={notes}
									maxLength={50}
									placeholder="请输入（最多50个字）"
									onChange={onTextChange}
									autoSize={{minRows: 3, maxRows: 3}}
								/>
							</div>
						</>
					)}

					<div />
				</div>
			) : (
				<></>
			)}
			{pageType === 'audit' || pageType === 'detail'  ?(
				<div>
					<div className={Styles.titleBox}>审批流程</div>
					<Examine
						ref={examineRef}
						examineType={false}
						orgId={routerQuery?.orgId}
						processInstanceId={routerQuery?.processId}
						bizType={14}
						bizNo={routerQuery.id}
						
					/>
				</div>
				
			):(<></>)}
			<Basics
				pageType={pageType}
				basicsForm={basicsForm}
				detailRecord={detailRecord}
				routerQuery={routerQuery}
				user={user}
				callback={(e: any) => {
					setEdType(e)
					setNumberAndAmountList([
						{
							correspondingLadder: '1',
							number: '',
							amount: '',
							ladderBd: '',
						},
					])
					setOffsetNumberAndAmountList([
						{
							correspondingLadder: '1',
							number: '',
							amount: '',
							ladderBd: '',
						},
					])
				}}
			/>
			<EditTb
				pageType={pageType}
				callBack={callBack}
				forms={formsN}
				setForms={setFormsN}
				edType={edType}
				andAmount={andAmount}
				num={1}
				list={numberAndAmountList}
				setList={setNumberAndAmountList}
			/>

			<EditTb
				pageType={pageType}
				forms={formsO}
				setForms={setFormsO}
				num={2}
				andAmount={andAmount}
				list={offsetNumberAndAmountList}
				setList={setOffsetNumberAndAmountList}
			/>

			{/* <Reward
        channelCodeList={channelCodeList}
        setChannelCodeList={setChannelCodeList}
        pageType={pageType}
        detailRecord={detailRecord}
        offsetList={offsetList}
        setOffsetList={setOffsetList}
      /> */}
			{routerQuery.type !== '1' ? (
				<Tb
					pageType={pageType}
					rederT={rederT}
					selectedRow={selectedRow}
					setSelectedRow={setSelectedRow}
					basicsForm={basicsForm}
				/>
			) : null}
			{routerQuery.type !== '1' ? (
				<div className={Styles.operation}>
					{pageType !== 'detail' && pageType !== 'audit' && (
						<Button
							type="primary"
							htmlType="submit"
							loading={loading}
							onClick={onSave}>
							保存
						</Button>
					)}
					{pageType === 'audit' && (
						<Button
							type="primary"
							htmlType="submit"
							loading={loading}
							onClick={onCompleteTask}>
							保存
						</Button>
					)}
					{/* {pageType === 'audit' && routerQuery?.examine ? (
					<>
						<Button
							style={{marginRight: '50px'}}
							type="primary"
							htmlType="submit"
							onClick={() => {
								setExamineType('同意')
								setIsExamineModalOpen(true)
							}}>
							同意
						</Button>
						<Button
							onClick={() => {
								setExamineType('驳回')
								setIsExamineModalOpen(true)
							}}>
							驳回
						</Button>
						<Button
							style={{marginLeft: '50px', marginRight: '50px'}}
							onClick={() => {
								setExamineType('拒绝')
								setIsExamineModalOpen(true)
							}}>
							拒绝
						</Button>
					</>
				) : (
					<></>
				)} */}

					<Button
						style={{marginLeft: '5px;'}}
						onClick={() => {
							history.go(-1)
						}}>
						取消
					</Button>
					{/* <Modal
					text={`确定要${examineType}吗？请仔细核对所填信息`}
					loading={btnLoading}
					onSubmit={onCompleteTask}
					isModalOpen={isExamineModalOpen}
					setIsModalOpen={setIsExamineModalOpen}
				/> */}
				</div>
			) : null}
		</div>
	)
}
export default connect(({user}: any) => ({user}))(add)
